package leetcode_201_300;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LeeCode_210 {
    public static void main(String[] args) {

    }
    private static int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] du = new int[numCourses];
        List<List<Integer>> ad = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            ad.add(new ArrayList<>());
        }
        LinkedList<Integer> queue = new LinkedList<>();
        for (int[] p : prerequisites) {
            du[p[0]]++;
            ad.get(p[1]).add(p[0]);
        }
        for (int i = 0; i < numCourses; i++) {
            if (du[i] == 0)
                queue.add(i);
        }
        int[] ans = new int[numCourses];
        int index = 0;
        while (!queue.isEmpty()){
            int pre = queue.poll();
            numCourses--;
            ans[index++] = pre;
            for (int cur : ad.get(pre)) {
                if (--du[cur] == 0){
                    queue.add(cur);
                }
            }
        }
        return numCourses == 0 ? ans : new int[0];
    }
}
